package com.dp.mallchat.common.common.inteceptor;

import cn.hutool.extra.servlet.ServletUtil;
import com.dp.mallchat.common.common.domain.dto.RequestInfo;
import com.dp.mallchat.common.common.utils.RequestHolder;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * @Author: dupeng
 * @CreateTime: 2024-06-03  15:32
 * @Description: web 请求收集
 */
@Order(2)
@Component
public class CollectorInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setUid(Optional.ofNullable(request.getAttribute(TokenInterceptor.ATTRIBUTE_UID)).map(Object::toString).map(Long::valueOf).orElse(null));
        requestInfo.setIp(ServletUtil.getClientIP(request));
        RequestHolder.setThreadLocal(requestInfo);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        RequestHolder.remove();
    }
}
